package com.yijia.work4.question5.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 可以作为登录拦截器
 */
public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpSession session = request.getSession();
        Object o = session.getAttribute("currentUser");//获取currentUser
        String path = request.getServletPath();//获取请求路径

        if (o == null && path.indexOf("login")<0){//未登录且不是登录页面则转发到登录页面
            request.getRequestDispatcher("login.jsp").forward(servletRequest,servletResponse);

        }else {
            filterChain.doFilter(servletRequest,servletResponse);

        }
    }

    @Override
    public void destroy() {

    }
}
